package cn.wyl.pet.service.impl;

import cn.wyl.basic.exception.BusinessException;
import cn.wyl.basic.util.*;
import cn.wyl.order.domain.OrderPetAcquisition;
import cn.wyl.order.mapper.OrderPetAcquisitionMapper;
import cn.wyl.order.service.delay.Consumer;
import cn.wyl.order.service.delay.Producer;
import cn.wyl.org.domain.Employee;
import cn.wyl.org.domain.Shop;
import cn.wyl.org.mapper.EmployeeMapper;
import cn.wyl.org.mapper.ShopMapper;
import cn.wyl.pet.domain.Pet;
import cn.wyl.pet.domain.SearchMasterMsg;
import cn.wyl.pet.domain.SearchMasterMsgAuditLog;
import cn.wyl.pet.mapper.PetMapper;
import cn.wyl.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.wyl.pet.mapper.SearchMasterMsgMapper;
import cn.wyl.pet.query.SearchMasterMsgQuery;
import cn.wyl.pet.service.ISearchMasterMsgService;
import cn.wyl.basic.service.impl.BaseServiceImpl;
import cn.wyl.user.domain.Logininfo;
import cn.wyl.user.domain.User;
import cn.wyl.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    ShopMapper shopMapper;
    @Autowired
    EmployeeMapper employeeMapper;
    @Autowired
    SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    PetMapper petMapper;
    @Autowired
    OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Transactional
    @Override
    public AxiousResult publish(SearchMasterMsg searchMasterMsg, HttpServletRequest request) {
        try {
            //获取发布寻主消息的用户
            Logininfo logininfo = LoginContext.getLogininfo(request);
            User user =userMapper.loadByLogininfoId(logininfo.getId());

            //1.添加user_id
            searchMasterMsg.setUserId(user.getId());
            //百度地图工具地址转换成Point类，搜索50公里以内最近店铺
            Point point = DistanceUtils.getPoint(searchMasterMsg.getAddress());
            Shop nearestShop = DistanceUtils.getNearestShop(point, shopMapper.loadAll());
            //搜索失败
            if (nearestShop==null){
              return new AxiousResult(false,"发布失败，附近没有店铺!");
            }
            // 绑定店铺shop_id
            searchMasterMsg.setShopId(nearestShop.getId());
            // 为数据库表t_search_master_msg添加寻主消息
            searchMasterMsgMapper.save(searchMasterMsg);

            //智能审核
            //文字审核
            Boolean textBoo1 = BaiduAuditUtils.TextCensor(searchMasterMsg.getTitle() );
            Boolean textBoo2 = BaiduAuditUtils.TextCensor(searchMasterMsg.getName() );
            Boolean textBoo3 = BaiduAuditUtils.TextCensor(searchMasterMsg.getAddress());
            //图片审核
            Boolean imageBoo = BaiduAuditUtils.ImgsCensor(searchMasterMsg.getResources());
            if (textBoo1&&textBoo2&&textBoo3&&imageBoo){
                //审核通过： 修改寻主消息状态1【审核通过待处理】 + 将当前寻主消息分配给最近的门店 + 发短信告诉它 + 添加审核日志
                searchMasterMsg.setState(1);
                searchMasterMsg.setNote("审核通过");
                //更新
                searchMasterMsgMapper.update(searchMasterMsg);

                //模拟发短信或发邮件
                //String shopAdminPhone = employeeMapper.loadById(nearestShop.getAdmin_id()).getPhone();
                //SendMsgUtil.sendMsg(shopAdminPhone, "你有新的订单，请尽快处理："+searchMasterMsg.getTitle());
                System.out.println("你有新的订单，请尽快处理："+searchMasterMsg.getTitle());

                //添加审核日志
                SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
                log.setMsgId(searchMasterMsg.getId());
                log.setState(1);
                //audit_id 默认为null, 表示自动审核
                log.setNote("审核通过");
                searchMasterMsgAuditLogMapper.save(log);


            }else {
                //为数据库表t_search_master_msg更新寻主消息
                searchMasterMsg.setState(-1);
                searchMasterMsg.setNote("审核失败,内容非法");
                //更新
                searchMasterMsgMapper.update(searchMasterMsg);

                //添加审核日志
                SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
                log.setMsgId(searchMasterMsg.getId());
                log.setState(0);//审核失败
                log.setNote("审核失败，内容非法");
                searchMasterMsgAuditLogMapper.save(log);
                return new AxiousResult(false,"审核失败，内容非法!");
            }

            return new AxiousResult();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AxiousResult(false,"发布失败!");


    }

    /**
     * 查询待处理订单 即根据登录人的shopid 取寻主消息中查找state为1 shopid！null的信息
     * @param query
     * @param request
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
            query.setState(1);
            Logininfo logininfo = LoginContext.getLogininfo(request);
            Employee employee= employeeMapper.loadByLogininfoId(logininfo.getId());
            // 判断当前管理员有shopid没，有就查询指定shopid的寻主消息，没有就查询所有寻主消息
            if (employee.getShop_id()!=null){
                query.setShopId(employee.getShop_id());
            }
            return super.queryPage(query);
    }
    @Transactional
    @Override
    public AxiousResult reject(Long id) {
        try {
            searchMasterMsgMapper.reject(id);
            return new AxiousResult(true,"成功",null);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AxiousResult(false,"失败",null);

    }

    @Override
    public void acceptOrder(Map<String, Object> params) {

        Long msgId = Long.valueOf(params.get("msgId").toString());
        //获取寻主消息
        SearchMasterMsg msg = searchMasterMsgMapper.loadById(msgId);

        // 获取收购人id
        Long employeeId = Long.valueOf(params.get("handler").toString());
        String note = params.get("note").toString();

        //1.校验接单表里是否有这条寻主Id,如果有则有人接单
       if (orderPetAcquisitionMapper.loadByMsgId(msgId)!=null){
           throw new BusinessException("已经被接单，正在处理中！");
       }

       //创建宠物信息
        Pet pet=searchMasterMsg2Pet(msg);
        petMapper.save(pet);

        //创建宠物收购订单
        OrderPetAcquisition order=buildPetAcquisitionOrder(msg,employeeId,pet);
        orderPetAcquisitionMapper.save(order);
        try {
            Consumer.consume(orderPetAcquisitionMapper);
            Producer.produceOrder(order.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public OrderPetAcquisition buildPetAcquisitionOrder(SearchMasterMsg msg,Long employeeId,Pet pet){

        OrderPetAcquisition order = new OrderPetAcquisition();
        //根据收购人Id生成订单编号
        String orderSn = CodeGenerateUtils.generateOrderSn(employeeId);
        order.setOrderSn(orderSn);
        order.setDigest(msg.getName()+"的收购订单");
        //最后收购是当前时间+2两天
        long lastcomfirmtimeLong = System.currentTimeMillis()+1000*60*60*24*2;
        order.setLastcomfirmtime(new Date(lastcomfirmtimeLong));
        order.setState(0);
        order.setPrice(msg.getPrice());
        //        order.setPaytype(); //现金支付
        order.setPetId(pet.getId());
        order.setUserId(msg.getUserId());
        order.setShopId(msg.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(employeeId);
        order.setSearchMasterMsgId(msg.getId());
        return order;
    }

    private Pet searchMasterMsg2Pet(SearchMasterMsg searchMasterMsg) {
        Pet pet = new Pet();
        pet.setName(searchMasterMsg.getName());
        pet.setResources(searchMasterMsg.getResources());
        pet.setTypeId(searchMasterMsg.getPetType());
        //就要获取处理人的店铺id
        pet.setShopId(searchMasterMsg.getShopId());
        pet.setSearchMasterMsgId(searchMasterMsg.getId());
        //用户发布时需要的价格 收购回来就是成本价
        pet.setCostprice(searchMasterMsg.getPrice());
        //宠物才被收购暂无领养人id，即userid
        //默认下架状态
        pet.setState(0);
        return pet;
    }
}
